﻿namespace IteratorPattern
{
    internal class Program
    {
        static void Main(string[] args)
        {
            Iterator iterator;
            IListCollection list = new ConcreteList();
            iterator = list.GetIterator();

            while (iterator.MoveNext()) 
            {
                int i = (int)iterator.GetCurrent();
                Console.WriteLine(i.ToString());
                iterator.Next();
            }
            Console.Read();
        }
    }

    // 抽象聚合类
    public interface IListCollection 
    {
        Iterator GetIterator();
    }

    // 迭代器抽象类
    public interface Iterator 
    {
        bool MoveNext();
        object GetCurrent();
        void Next();
        void Reset();
    }

    // 具体聚合类
    public class ConcreteList : IListCollection 
    {
        int[] collection;
        public ConcreteList() 
        {
            collection = new int[] { 2, 4, 6, 8 }; 
        }
        public Iterator GetIterator() 
        {
            return new ConcreteItenator(this);
        }
        public int Length 
        {
            get 
            {
                return collection.Length;
            }
        }
        public int GetElement(int index) 
        {
            return collection[index];
        }
    }

    // 具体迭代器类
    public class ConcreteItenator : Iterator 
    {
        private ConcreteList _list;
        private int _index;
        public ConcreteItenator(ConcreteList list)
        {
            _list = list;
            _index = 0;
        }

        public bool MoveNext() 
        {
            if (_index < _list.Length) 
            {
                return true;
            }
            return false;
        }

        public object GetCurrent() 
        {
            return _list.GetElement( _index);
        }

        public void Reset() 
        {
            _index = 0;
        }

        public void Next()
        {
            if (_index < _list.Length) 
            {
                _index++;
            }
        }
    }






}
